package com.atguigu.tingshu.user.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.annotation.login.LoginRequired;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.config.jwt.JwtConstantsProperties;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.interfaces.RSAPrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 微信授权登录接口
 * </p>
 *
 * @author sun
 * @since 2023-05-06 11:02
 */
@RestController
@RequestMapping("/api/user/wxLogin")
@Slf4j
public class WxLoginApiController {

    @Resource
    private UserInfoService userInfoService;
    @Resource
    private WxMaService wxMaService;
    @Resource
    private JwtConstantsProperties jwtConstantsProperties;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/wxLogin/{code}")
    @SneakyThrows
    public Result<Map<String, Object>> wxLogin(@PathVariable("code") String code) {
        // 获取OpeId

        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
        String openid = sessionInfo.getOpenid();

        // 查询是否是初次登录
        List<UserInfo> userInfos = userInfoService.list(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openid));
        UserInfo userInfo = !userInfos.isEmpty() ? userInfos.getFirst() : null;
        if (userInfo == null) {
            userInfo = UserInfo.builder()
                    .wxOpenId(openid)
                    .nickname("听友" + System.currentTimeMillis())
                    .avatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg")
                    .build();
            // 插入用户信息
            userInfoService.save(userInfo);
            // 新建用户的账户信息
            rabbitTemplate.convertAndSend("account_exchange", "user_account_init", userInfo.getId().toString());

        }
        // 先查redis中是否发放了token
        String token = redisTemplate.opsForValue().get("user:login:token:" + userInfo.getId());
        if(token != null){
            //  验证token
            Jwt jwt = JwtHelper.decodeAndVerify(token, new RsaVerifier(SystemConstant.JWT_PUBLIC_KEY));
            //  解析token
            String claims = jwt.getClaims();
            Map map = JSONObject.parseObject(claims, Map.class);
            Long userId = Long.valueOf((String.valueOf(map.get(SystemConstant.JWT_CLEAMS_USER_ID))));
            // 如果用户id不一致，重新生成token
            if (!userId.equals(userInfo.getId())) {
                // 生成token
                token = getToken(userInfo);
            }
        } else {
            // redis中无token，生成新token
            token = getToken(userInfo);
        }
        // 在redis中设置token的过期时间
        redisTemplate.opsForValue().set("user:login:token:" + userInfo.getId(), token, 2 * 60 * 60, TimeUnit.MINUTES);
        // 封装返回结果
        HashMap<String, Object> result = new HashMap<>();
        result.put("token", token);
        return Result.ok(result);
    }

    /**
     * 生成token
     * @param userInfo 用户信息
     * @return token
     */
    private String getToken(UserInfo userInfo) {
        String token;
        Map<String, Object> jsonObject = new HashMap<>();
        jsonObject.put(SystemConstant.JWT_CLEAMS_USER_ID, userInfo.getId());
        jsonObject.put(SystemConstant.JWT_CLEAMS_USER_NAME, userInfo.getNickname());
        token = JwtHelper.encode(JSON.toJSONString(jsonObject),
                        new RsaSigner((RSAPrivateKey) jwtConstantsProperties.getPrivateKey()))
                .getEncoded();
        return token;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getUserInfo")
    @LoginRequired
    public Result<UserInfoVo> getUserInfo() {

        return Result.ok(userInfoService.getUserInfoVo());
    }


}
